package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.AreaService;
import co.gov.medellin.ssti.sub.model.service.ProgramaService;
import co.gov.medellin.ssti.sub.model.service.RepBeneficioOtorgadoService;
import co.gov.medellin.ssti.sub.model.service.RepDetBeneficiarioService;
import co.gov.medellin.ssti.sub.model.service.SedeService;
import co.gov.medellin.ssti.sub.model.service.SubprogramaService;
import co.gov.medellin.ssti.sub.model.vo.AreaVO;
import co.gov.medellin.ssti.sub.model.vo.ProgramaVO;
import co.gov.medellin.ssti.sub.model.vo.RepDetBeneficiarioVO;
import co.gov.medellin.ssti.sub.model.vo.SedeVO;
import co.gov.medellin.ssti.sub.model.vo.SubprogramaVO;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;

public class ReportDetBeneficiarioAction extends Action {
	@Autowired
	AreaService areaServiceImpl;
	@Autowired
	ProgramaService programaServiceImpl;
	@Autowired
	RepBeneficioOtorgadoService repBeneficioOtorgadoServiceImpl;
	@Autowired
	RepDetBeneficiarioService repDetBeneficiarioServiceImpl;
	@Autowired
	SedeService sedeServiceImpl;
	@Autowired
	SubprogramaService subprogramaServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		Object codePrograma = (Object) request.getParameter("codePrograma");

		HttpSession session = request.getSession();
		UserVO user = (UserVO) session.getAttribute("userInfo");
		session.removeAttribute("msg");
		session.setAttribute("msg", "");
		Collection<AreaVO> areas = null;
		Collection<ProgramaVO> programas = null;
		Collection<SubprogramaVO> subprogramas = null;
		Collection<SedeVO> sedes = null;

		session.removeAttribute("Beneficiario");
		session.removeAttribute("errorfecha");
		session.removeAttribute("ListaFiltrado");
		String fechaInicial = request.getParameter("fechaInicial");
		String fechaFinal = request.getParameter("fechaFinal");
		String strarea = request.getParameter("codearea");

		try {
			sedes = sedeServiceImpl.loadAllSedes();
		} catch (DAOException e) {
			SUBException.logDebugError("", e);
		}
		if (sedes.size() > 0) {
			session.setAttribute("sedes", sedes);
			try {
				areas = areaServiceImpl
						.findAreasAuthorized(String.valueOf(user.getCode()),
								user.getUserGroupName());
			} catch (DAOException e) {
				SUBException.logDebugError("", e);
			}

			if (areas.size() > 0) {
				session.setAttribute("areas", areas);

				if ((Object) strarea != null && !strarea.equals("nulo")) {
					session.removeAttribute("programas");
					session.removeAttribute("subprogramas");

					try {
						ProgramaVO objProgramaVO = new ProgramaVO();
						objProgramaVO.setCodeArea(new Long(strarea));
						programas = (List<ProgramaVO>) programaServiceImpl
								.findProgramaByCriteria(objProgramaVO,
										user.getUserGroupName(),
										user.getCode(), user.getCodeArea());
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}
					if (programas.size() > 0) {
						session.setAttribute("programas", programas);
					}

				} else {
					try {
						programas = repBeneficioOtorgadoServiceImpl
								.findProgramaByUserReport(user.getCode(),
										user.getUserGroupName(),
										user.getCodeArea());
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}
					session.removeAttribute("msg");
					if (programas.size() > 0) {
						session.setAttribute("programas", programas);
					} else {
						session.setAttribute("msg",
								"No se encontraron programas vigentes a la fecha..");
					}
				}
				if (codePrograma != null) {

					String codpro = (String) codePrograma;
					if (!codpro.equals("")) {
						try {
							String strCodeProg = (String) codePrograma;
							SubprogramaVO vo = new SubprogramaVO();
							vo.setCodePrograma(Long.valueOf(strCodeProg));
							subprogramas = subprogramaServiceImpl
									.findAllowedSubprograma(vo, user.getCode(),
											user.getUserGroupName(),
											user.getCodeArea());
						} catch (DAOException e) {
							SUBException.logDebugError("", e);
						}
						session.removeAttribute("msg");
						if (subprogramas.size() > 0) {
							session.setAttribute("subprogramas", subprogramas);
						} else {
							session.setAttribute("msg",
									"No se encontraron subprogramas asociados a este programa que esten vigentes..");
						}
					} else {
						session.setAttribute("msg", "");
						session.removeAttribute("subprogramas");
					}
				}
			} else {
				session.setAttribute("msg", "No se encontraron areas..");
			}
		} else {
			session.setAttribute("msg",
					"No se encontraron sedes vigentes a la fecha..");
		}

		Object accion = request.getParameter("acciones");
		Object codeSede = request.getParameter("code");
		Object codeSubprograma = request.getParameter("codeSubPrograma");
		// Object desde = request.getParameter("desde");
		// Object hasta = request.getParameter("hasta");
		// Object cantidad = request.getParameter("cantidad");
		String codeSede1 = (String) codeSede;
		if (codeSede1 != null
				&& (codeSede1.equalsIgnoreCase("nulo") || codeSede1.isEmpty())) {
			codeSede1 = null;
		}

		String codeSubprograma1 = (String) codeSubprograma;
		if (codeSubprograma1 != null
				&& (codeSubprograma1.equalsIgnoreCase("nulo") || codeSubprograma1
						.isEmpty())) {
			codeSubprograma1 = "";
		}

		String codePrograma1 = (String) codePrograma;
		if (codePrograma1 != null
				&& (codePrograma1.equalsIgnoreCase("nulo") || codePrograma1
						.isEmpty())) {
			codePrograma1 = null;
		}

		String accion1 = (String) accion;
		session.removeAttribute("beneficiosSede");
		if (accion1 != null && accion1.equals("BuscarTodo")) {
			int cobeneficio = 0;
			try {
				RepDetBeneficiarioVO objDetBeneVO = new RepDetBeneficiarioVO();
				if (codeSede1 != null) {
					objDetBeneVO.setCodeSede(new Long((String) codeSede));
				}
				if (codePrograma1 != null) {
					objDetBeneVO
							.setCodePrograma(new Long((String) codePrograma));
				}
				if (codeSubprograma1 != null && !codeSubprograma1.isEmpty()) {
					objDetBeneVO.setCodeSubprograma(new Long(
							(String) codeSubprograma));
				}
				if (fechaInicial != null && !fechaInicial.isEmpty()) {

					objDetBeneVO.setDesde(fechaInicial);
				}
				if (fechaFinal != null && !fechaFinal.isEmpty()) {
					objDetBeneVO.setHasta(fechaFinal);

				}

				repDetBeneficiarioServiceImpl.findFiltros(objDetBeneVO);
				session.setAttribute("Parametros", objDetBeneVO);
				cobeneficio = repDetBeneficiarioServiceImpl
						.findCantidadBeneficiariosByCriteria(objDetBeneVO);
				if (cobeneficio > 0) {
					objDetBeneVO = null;
				} else {
					session.setAttribute("msg",
							"No hay registros que cumplan con los filtros seleccionados");
					return mapping.findForward("success");
				}
			} catch (DAOException e) {
				SUBException.logDebugError("", e);
			}
		}

		Object obIR = request.getParameter("seleccionar");
		if (obIR == null || accion.equals("BuscarSubprogrmas")
				|| accion.equals("areas")) {
			session.setAttribute("limpiar", "Si");
			return mapping.findForward("success");
		} else {
			session.setAttribute("limpiar", "Si");
			return mapping.findForward("ir");
		}

	}
}